package com.pz.account.service;


import com.pz.account.domain.model.MemberLoginParams;
import com.pz.account.domain.model.MemberLoginUser;
import com.pz.art.domain.AssoMember;
import com.pz.art.service.MemberService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.LoginParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Objects;

import static com.alibaba.druid.util.Utils.md5;


/**
 * 移动端登录服务接口
 */
@Component
public class MemberMobileLoginService {

    private static final Logger log = LoggerFactory.getLogger(MemberMobileLoginService.class);

    @Autowired(required = false)
    private MemberTokenService tokenService;


    @Autowired(required = false)
    private AuthenticationManager authenticationManager;

    @Autowired(required = false)
    private MemberService memberService;

    /**
     * 注入redis服务
     */
    @Autowired(required = false)
    private RedisCache redisCache;

    /**
     * 请求时间戳过期时间5分钟
     */
    private static final int REQUEST_TIME_OUT = 1000 * 60 * 5;


    /**
     * jwt密钥
     */
    @Value("${token.secret}")
    private String jwtSecretKey;

    public AjaxResult login(MemberLoginParams loginParams) {
        log.debug("login and loginParams:{}", loginParams);
        System.out.println(11);
        if (Objects.isNull(loginParams)) {
            return AjaxResult.error(-6, "登录参数不能为空");
        }
        String loginType = loginParams.getLoginType();
        if (StringUtils.isBlank(loginType)) {
            return AjaxResult.error(-6, "登录方式不能为空");
        }
        //登录方式0验证码登录，1用户名密码登录，2本机一键登录，3微信单点登录
        if (loginType.equals("0")) {
            String phoneNo = loginParams.getPhone();
            if (StringUtils.isBlank(phoneNo)) {
                return AjaxResult.error(-6, "登录名不能为空");
            }
            String validCode = loginParams.getValidCode();
            //2表示登录验证码，校验验证码合法性
            //sysSmsSendService.checkValidCode(phoneNo,validCode,"2");
            loginParams.setPhone(phoneNo);
            loginParams.setPassword("SSO_LOGIN");
        } else if (loginType.equals("1")) {
            String password = loginParams.getPassword();
            if (StringUtils.isBlank(password)) {
                return AjaxResult.error(-6, "密码不能为空");
            }
        }
        // 用户验证
        Authentication authentication = null;
        try {
            //进行用户验证，去查找会员表中是否存在该会员，如果不存在则进行注册
            String password = (md5(loginParams.getPassword()));
            AssoMember member = memberService.selectMemberByPhoneNo(loginParams.getName());
            if (Objects.isNull(member)){
               return AjaxResult.error("该手机号未注册");
            }
            if (Objects.isNull(member.getUnit_id())){
                member.setMember_unit_name("普通会员");
            } else {
                member.setMember_unit_name(memberService.getAssomemberByUnitId(Long.valueOf(member.getUnit_id())).get(0).getMember_unit_name());
            }
            System.out.println("111222333");
            System.out.println(password);
            System.out.println(member.getPassword());
            //判断密码不等于输入密码即返回密码错误
            if (!member.getPassword().equals(password)){
                return AjaxResult.error("密码错误");
            }

            MemberLoginUser loginUser = new MemberLoginUser();

            loginUser.setId(Long.valueOf(member.getId()));
            // 生成token
            String token = IdUtils.fastUUID();
//            String token = tokenService.createMemberToken(loginUser);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginParams.getName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            this.recordsMemeberLoginInfo(loginUser.getId());
            AjaxResult ajax = AjaxResult.success("");
            System.out.println("=====ts=====");
            System.out.println(token);
            System.out.println(loginUser.getUser());
            ajax.put("token", token);
            //token过期时间
            ajax.put("expired", loginUser.getExpireTime());
            ajax.put("user", member);
            ajax.put("isAgent", String.valueOf(true));
            return ajax;
//            System.out.println("获取权");
//            System.out.println(loginParams.getName());
//            System.out.println(loginParams.getPassword());
//            authentication = authenticationManager
//                    .authenticate(new UsernamePasswordAuthenticationToken(loginParams.getName(), loginParams.getPassword()));

        } catch (Exception e) {
            System.out.println(e);
            System.out.println(e.getStackTrace());
            return AjaxResult.error(-8, "密码错误");
        }
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        //loginUser.setSource("app");
//        SysUser user = loginUser.getUser();
//        // 生成token
//        String token = tokenService.createMemberToken(loginUser);
//        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginParams.getName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
//        this.recordsMemeberLoginInfo(user.getUserId());
        //判断用户是否存在管理员角色
        // 角色集合
//        Set<String> roles = permissionService.getRolePermission(user);
//        boolean roleFlag = false;
//        if(!CollectionUtils.isEmpty(roles)){
//            for (String roleKey : roles) {
//                if(roleKey.equals("agent")){
//                    roleFlag = true;
//                    break;
//                }
//            }
//        }

    }

    /**
     * 发送注册验证码
     *
     * @param loginParams
     * @return
     */
    public AjaxResult sendCode(MemberLoginParams loginParams) {
        if (Objects.isNull(loginParams)) {
            return AjaxResult.error(-6, "参数为空");
        }
        // 验证验证码
        if (StringUtils.isBlank(loginParams.getPhone())) {
            return AjaxResult.error(-6, "发送手机号不能为空");
        }
        String validCodeType = "2";
        if (StringUtils.isNotBlank(loginParams.getValidCodeType())) {
            validCodeType = loginParams.getValidCodeType();
        }
        try {
            //SysSmsSend sysSmsSend = sysSmsSendService.sendMessage(loginParams.getPhoneNo(),validCodeType,true);
            //String resultFlag = sysSmsSend.getResultFlag();
            String resultFlag = "n";
            if (resultFlag.equals("f")) {
                return AjaxResult.error(-6, "对不起手机号【" + loginParams.getPhone() + "】发送短信失败：失败原因:");
            }
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        AjaxResult ajax = AjaxResult.success("验证码发送成功");
        return ajax;
    }

    /**
     * 手机号验证码注册用户
     *
     * @param loginParams
     * @return
     */
    @Transactional(readOnly = false)
    public AjaxResult registerUser(MemberLoginParams loginParams) {
        try {
            if (Objects.isNull(loginParams)) {
                return AjaxResult.error(-6, "参数为空");
            }
            String phoneNo = loginParams.getPhone();
            if (StringUtils.isBlank(phoneNo)) {
                return AjaxResult.error(-6, "发送手机号不能为空");
            }
            String validCode = loginParams.getValidCode();
            if (StringUtils.isBlank(validCode)) {
                return AjaxResult.error(-6, "验证码不能为空");
            }
            loginParams.setName(phoneNo);
            loginParams.setPassword(phoneNo);
            loginParams.setLoginType("1");
            return this.login(loginParams);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 设置注册用户角色部门岗位信息
     *
     * @param registerUser
     * @return
     */
    private void setUserDefaultInfo(AssoMember registerUser) {
        String registerRoleCode = DictUtils.getDictValue("sys_config", "register_role_code", "");
        if (StringUtils.isBlank(registerRoleCode)) {
            throw new ServiceException("请前往数据字典【sys_config】中维护注册用户角色编码【register_role_code】");
        }
        String registerDeptCode = DictUtils.getDictValue("sys_config", "register_dept_code", "");
        if (StringUtils.isBlank(registerDeptCode)) {
            throw new ServiceException("请前往数据字典【sys_config】中维护注册用户部门编码【register_dept_code】");
        }
        String registerPostCode = DictUtils.getDictValue("sys_config", "register_post_code", "");
        if (StringUtils.isBlank(registerPostCode)) {
            throw new ServiceException("请前往数据字典【sys_config】中维护注册用户岗位编码【register_post_code】");
        }

    }


    public void recordsMemeberLoginInfo(Long userId) {
        AssoMember assoMember = new AssoMember();
        assoMember.setId(Math.toIntExact(userId));
        assoMember.setLogin_ip(IpUtils.getIpAddr());
        assoMember.setLogin_time(DateUtils.getNowDate());
        assoMember.setUpdateTime(DateUtils.getNowDate());
        memberService.updateMember(assoMember);
    }

}
